import React, { useEffect, useRef, useState, useCallback } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { getCanvasCenter } from '../utils';

interface VideoSegment {
    id: string;
    material_id: string;
    target_timerange: {
        start: number;
        duration: number;
    };
    source_timerange: {
        start: number;
        duration: number;
    };
    clip: {
        alpha: number;
        scale: { x: number; y: number };
        rotation: number;
        transform: { x: number; y: number };
        flip: { horizontal: boolean; vertical: boolean };
    };
    material_info: {
        id: string;
        name: string;
        public_url: string;
        width: number;
        height: number;
        duration: number;
    };
    currentTrackIndex?: number; // 当前轨道层级
}

interface VideoLayerProps {
    draftData: any;
    canvasWidth?: number; // 不再使用，但保留接口兼容性
    canvasHeight?: number; // 不再使用，但保留接口兼容性
}

// 判断是否为视频文件
const isVideoFile = (url: string): boolean => {
    const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v', '.3gp', '.ogv'];
    const lowerUrl = url.toLowerCase();
    return videoExtensions.some((ext) => lowerUrl.includes(ext));
};

const VideoLayer: React.FC<VideoLayerProps> = ({ draftData }) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const videoRefs = useRef<{ [key: string]: HTMLVideoElement }>({});
    const [videoSegments, setVideoSegments] = useState<VideoSegment[]>([]);
    const isPlayingRef = useRef<boolean>(false);
    
    // 防抖定时器引用
    const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

    // 从Redux获取播放状态
    const currentTime = useSelector((state: RootState) => state.timeline.currentTime);
    const isPlaying = useSelector((state: RootState) => state.timeline.isPlaying);

    // 更新播放状态引用
    useEffect(() => {
        isPlayingRef.current = isPlaying;
    }, [isPlaying]);

    // 防抖更新视频片段数据
    const debouncedUpdateVideoSegments = useCallback((newSegments: VideoSegment[]) => {
        // 清除之前的定时器
        if (debounceTimerRef.current) {
            clearTimeout(debounceTimerRef.current);
        }
        
        // 设置防抖定时器
        debounceTimerRef.current = setTimeout(() => {
            setVideoSegments(newSegments);
        }, 100); // 100ms 防抖延迟
    }, []);

    // 提取视频片段数据
    useEffect(() => {
        if (!draftData?.script_content?.tracks) {
            setVideoSegments([]);
            return;
        }
        const tracks = draftData.script_content.tracks;
        // 使用 filter 和 flatMap 提取视频片段
        const segments: VideoSegment[] = tracks
            .filter((track: any) => {
                console.log('轨道信息:', track);
                return track.type === 'video' && track.segments;
            })
            .flatMap((track: any, trackIndex: number) =>
                track.segments
                    .filter((segment: any) => segment.material_info && segment.material_info.public_url && isVideoFile(segment.material_info.public_url))
                    .map((segment: any) => ({
                        ...segment,
                        currentTrackIndex: trackIndex,
                    }))
            )
            .map((segment: any) => ({
                id: segment.id,
                material_id: segment.material_id,
                target_timerange: segment.target_timerange,
                source_timerange: segment.source_timerange,
                clip: segment.clip,
                material_info: segment.material_info,
                currentTrackIndex: segment.currentTrackIndex,
            }));
        debouncedUpdateVideoSegments(segments);
    }, [draftData, debouncedUpdateVideoSegments]);

    // 组件卸载时清理定时器
    useEffect(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);

    // 同步视频播放时间 - 简化版本，避免循环依赖
    useEffect(() => {
        console.log('videoSegments', videoSegments);
        if (videoSegments.length === 0) return;

        const updateVideos = () => {
            videoSegments.forEach((segment) => {
                const video = videoRefs.current[segment.id];
                if (!video) return;

                // 计算是否应该显示
                const startTime = segment.target_timerange.start / 1000;
                const endTime = startTime + segment.target_timerange.duration / 1000;
                const shouldShow = currentTime >= startTime && currentTime <= endTime;
                if (!shouldShow) {
                    video.pause();
                    return;
                }
                // 计算视频时间
                const targetStartTime = segment.target_timerange.start / 1000;
                const sourceStartTime = segment.source_timerange.start / 1000;
                const relativeTime = currentTime / 1000 - targetStartTime;
                const segmentTime = sourceStartTime + relativeTime;
                const currentVideoTime = video.currentTime;
                // 只有当时间差超过0.1秒时才更新，避免频繁更新
                if (Math.abs(currentVideoTime - segmentTime) > 0.1) {
                    video.currentTime = segmentTime;
                }
            });
        };

        const timeoutId = setTimeout(updateVideos, 16);
        return () => clearTimeout(timeoutId);
    }, [currentTime]); // 只依赖 currentTime

    // 控制视频播放/暂停 - 简化版本
    useEffect(() => {
        if (videoSegments.length === 0) return;

        videoSegments.forEach((segment) => {
            const video = videoRefs.current[segment.id];
            if (!video) return;

            // 计算是否应该显示
            const startTime = segment.target_timerange.start / 1000;
            const endTime = startTime + segment.target_timerange.duration / 1000;
            const shouldShow = currentTime >= startTime && currentTime <= endTime;

            if (!shouldShow) {
                video.pause();
                return;
            }

            // 检查视频是否已经暂停，避免重复操作
            if (isPlaying && video.paused) {
                // 使用 Promise 处理播放请求，避免中断错误
                const playPromise = video.play();
                if (playPromise !== undefined) {
                    playPromise.catch((error) => {
                        // 忽略播放中断错误
                        if (error.name !== 'AbortError') {
                            console.error('Video play error:', error);
                        }
                    });
                }
            } else if (!isPlaying && !video.paused) {
                video.pause();
            }
        });
    }, [isPlaying, currentTime]); // 只依赖这两个状态

    // 使用 calcMaterialSize 计算视频尺寸和位置
    const getVideoStyle = (segment: VideoSegment) => {
        // 根据轨道层级设置 zIndex，层级越大的显示在上层
        // 视频图层基础zIndex为1000，确保在底层
        const zIndex = segment.currentTrackIndex || 0;
        console.log(`视频素材的zindex`, zIndex);

        // 获取画布中心位置
        const canvasCenter = getCanvasCenter();
        console.log('视频画布中心', canvasCenter);

        // 计算视频占满画布的尺寸
        const fullCanvasWidth = canvasCenter.x * 2; // 画布宽度
        const fullCanvasHeight = canvasCenter.y * 2; // 画布高度

        // 基础样式 - 默认占满整个画布
        const baseStyle = {
            position: 'absolute' as const,
            backgroundColor: 'transparent' as const,
            width: `${fullCanvasWidth}px`,
            height: `${fullCanvasHeight}px`,
            zIndex: zIndex,
        };

        // 只有当 clip 存在时才处理位置和变换
        if (segment.clip) {
            // 根据 transform 值计算偏移量
            // transform.x 和 transform.y 每 0.1 对应 150px
            const offsetX = (segment.clip.transform.x || 0) * 100; // 0.1 * 1500 = 150px
            const offsetY = (segment.clip.transform.y || 0) * 1000; // 0.1 * 1500 = 150px

            // 计算最终位置 - 减去元素自身尺寸的一半，让元素真正居中
            const finalX = canvasCenter.x + offsetX - fullCanvasWidth / 2;
            const finalY = canvasCenter.y + offsetY - fullCanvasHeight / 2;

            // 构建变换字符串 - 按正确顺序应用变换
            const transforms = [];

            // 1. 先应用缩放
            if (segment.clip.scale) {
                transforms.push(`scale(${segment.clip.scale.x || 1}, ${segment.clip.scale.y || 1})`);
            }

            // 2. 再应用旋转
            if (segment.clip.rotation) {
                transforms.push(`rotate(${segment.clip.rotation}deg)`);
            }

            // 3. 最后应用翻转
            if (segment.clip.flip) {
                const scaleX = segment.clip.flip.horizontal ? -1 : 1;
                const scaleY = segment.clip.flip.vertical ? -1 : 1;
                transforms.push(`scale(${scaleX}, ${scaleY})`);
            }

            return {
                ...baseStyle,
                left: `${finalX}px`,
                top: `${finalY}px`,
                opacity: segment.clip.alpha || 1,
                transform: transforms.length > 0 ? transforms.join(' ') : undefined,
                transformOrigin: 'center center',
            };
        }

        // 没有 clip 时使用默认定位（画布中心）
        return {
            ...baseStyle,
            left: `${canvasCenter.x - fullCanvasWidth / 2}px`, // 减去视频宽度的一半
            top: `${canvasCenter.y - fullCanvasHeight / 2}px`, // 减去视频高度的一半
        };
    };

    return (
        <div
            ref={containerRef}
            style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: 'transparent',
                zIndex: 1,
            }}
        >
            {videoSegments.map((segment) => {
                // 计算是否应该显示
                const startTime = segment.target_timerange.start / 1000;
                const endTime = startTime + segment.target_timerange.duration / 1000;
                const shouldShow = currentTime >= startTime && currentTime <= endTime;
                if (!shouldShow) return null;

                // 计算视频时间
                const targetStartTime = segment.target_timerange.start / 1000;
                const sourceStartTime = segment.source_timerange.start / 1000;
                const relativeTime = currentTime / 1000 - targetStartTime;
                const segmentTime = sourceStartTime + relativeTime;
                const videoStyle = getVideoStyle(segment);

                return (
                    <video
                        key={segment.id}
                        ref={(el) => {
                            if (el) {
                                videoRefs.current[segment.id] = el;
                            }
                        }}
                        src={segment.material_info.public_url}
                        style={{
                            ...videoStyle,
                            objectFit: 'contain', // 使用 contain 模式，保持宽高比
                            objectPosition: 'center', // 视频居中显示
                        }}
                        muted={true}
                        playsInline
                        preload="metadata"
                        onLoadedData={() => {
                            const video = videoRefs.current[segment.id];
                            if (video) {
                                video.currentTime = segmentTime;
                            }
                        }}
                        onTimeUpdate={() => {
                            // 当视频播放超出片段范围时暂停
                            const video = videoRefs.current[segment.id];
                            if (video && video.currentTime > segment.source_timerange.duration / 1000) {
                                video.pause();
                            }
                        }}
                    />
                );
            })}
        </div>
    );
};

export default VideoLayer;
